package cn.tedu.mall.order.listener;

import cn.tedu.mall.front.service.IFrontSkuService;
import cn.tedu.mall.order.mapper.OrderItemMapper;
import cn.tedu.mall.order.mapper.OrderMapper;
import cn.tedu.mall.pojo.order.dto.OrderAddCondition;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
@RocketMQTransactionListener
public class TransactionOrderAddListener implements RocketMQLocalTransactionListener {
    /**
     * 执行本地事务,减库存,生订单,发延迟消息
     * @param msg
     * @param arg
     * @return
     */
    @Autowired
    private IFrontSkuService skuService;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private OrderAddListenerRegister register;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        OrderAddCondition orderAddCondition=(OrderAddCondition)arg;
        return register.execut(orderAddCondition);
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String orderClass= (String) msg.getHeaders().get("name");
        if (orderClass!=null && orderClass.equals("localAdd")){
            //TODO
        }else if(orderClass!=null && orderClass.equals("seckillAdd")){
            //TODO
        }
        //检查订单 sn 从消息中解析sn
        String sn= (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        //查询到订单 return commit
        OmsOrder order=orderMapper.selectOrderBySn(sn);
        if (order!=null){
            //不能commit 检查是否存在orderItems
            Integer count=orderItemMapper.selectCountByOrderId(order.getId());
            if (count!=0){
                return RocketMQLocalTransactionState.COMMIT;
            }else{
                //TODO 可以选择在有订单,但是没有订单商品的时候,将订单删除
                log.debug("有订单,但是没订单商品,记录日志");
            }
        }
        //没查到 回退库存
        skuService.returnStock(sn);
        return RocketMQLocalTransactionState.ROLLBACK;
    }
    private void replenishOrder(OmsOrder omsOrder){
        //state 订单状态 默认 未支付0        已支付,已发货,待收货,已收货,已关闭1,已取消,已退单
        omsOrder.setState(0);
        //时间字段 创建时间 修改时间 订单新增时间
        LocalDateTime now=LocalDateTime.now();
        omsOrder.setGmtOrder(now);
        omsOrder.setGmtModified(now);
        omsOrder.setGmtCreate(now);
        //UNDO 添加加钱,并且追加校验规则
    }
}
